package com.zmc.product.infrastructure.bean.response;

import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：zmc
 * @Date：2024/10/31 10:51
 */

@Data
public class CategoryResp implements Serializable {

    private Long id;

    private Long parentId;

    private String name;

    private List<CategoryResp> children;


    /**
     * 递归获取树结构
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public static List<CategoryResp> constructMenuTree(List<CategoryResp> list, long parentId) {
        List<CategoryResp> returnList = new ArrayList<>();
        for (CategoryResp resp : list) {
            if (resp.getParentId() == parentId) {
                List<CategoryResp> children = constructMenuTree(list, resp.getId());
                if (!CollectionUtils.isEmpty(children)) {
                    resp.setChildren(children);
                }
                returnList.add(resp);
            }
        }
        return returnList;
    }
}
